<template>
    <div class="app-container">
        <SearchContent :queryParams="queryParams" @query="handleQuery" @reset="resetQuery">
            <el-col :span="6">
                <el-form-item label="区划编码" prop="regionCode">
                    <el-input
                        v-model="queryParams.regionCode"
                        placeholder="请输入区划编码"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="区划名称" prop="regionName">
                    <el-input
                        v-model="queryParams.regionName"
                        placeholder="请输入区划名称"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                </el-form-item>
            </el-col>

        </SearchContent>
        <div class="card-wrap paddingAll20" :model="queryParams" ref="queryForm" label-width="86px">
            <div class="table-title-wrap justify-end">
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button
                            type="primary"
                            plain
                            icon="el-icon-plus"
                            size="mini"
                            @click="handleAdd"
                            v-hasPermi="['system:region:add']"
                        >新增
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button
                            type="info"
                            plain
                            icon="el-icon-sort"
                            size="mini"
                            @click="toggleExpandAll"
                        >展开/折叠
                        </el-button>
                    </el-col>
                    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>
            </div>
            <el-table
                v-if="refreshTable"
                v-loading="loading"
                :data="regionList"
                row-key="regionId"
                :default-expand-all="isExpandAll"
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            >
                <el-table-column label="区划名称" prop="regionName"/>
                <el-table-column label="区划编码" align="center" prop="regionCode"/>
                <el-table-column label="区划路径" prop="completeRegionName"/>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-edit"
                            @click="handleUpdate(scope.row)"
                            v-hasPermi="['system:region:edit']"
                        >修改
                        </el-button>
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-plus"
                            @click="handleAdd(scope.row)"
                            v-hasPermi="['system:region:add']"
                        >新增
                        </el-button>
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-delete"
                            @click="handleDelete(scope.row)"
                            v-hasPermi="['system:region:remove']"
                        >删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>


        <!-- 添加或修改地区管理对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="父级区划" prop="parentRegionId">
                    <treeselect v-model="form.parentRegionId" :options="regionOptions" :normalizer="normalizer" placeholder="请选择父级区划"/>
                </el-form-item>
                <el-form-item label="区划编码" prop="regionId">
                    <el-input v-model="form.regionCode" placeholder="请输入区划编码"/>
                </el-form-item>
                <el-form-item label="区划名称" prop="regionName">
                    <el-input v-model="form.regionName" placeholder="请输入区划名称"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {listRegion, getRegion, delRegion, addRegion, updateRegion} from "@/api/system/region";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import SearchContent from "@/components/SearchContent/index.vue";

export default {
    name: "Region",
    components: {
        Treeselect,
        SearchContent
    },
    data() {
        return {
            // 按钮loading
            buttonLoading: false,
            // 遮罩层
            loading: true,
            // 显示搜索条件
            showSearch: true,
            // 地区管理表格数据
            regionList: [],
            // 地区管理树选项
            regionOptions: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 是否展开，默认全部展开
            isExpandAll: false,
            // 重新渲染表格状态
            refreshTable: true,
            // 区划名称时间范围
            daterangeUpdateTime: [],
            // 查询参数
            queryParams: {
                parentRegionId: undefined,
                regionName: undefined,
                regionCode: undefined,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                parentRegionId: [
                    {required: true, message: "父级区划不能为空", trigger: "change"}
                ],
                regionCode: [
                    {required: true, message: "区划编码不能为空", trigger: "blur"}
                ],
                regionName: [
                    {required: true, message: "区划名称不能为空", trigger: "blur"}
                ],
            }
        };
    },
    created() {
        this.getList();
    },
    methods: {
        /** 查询地区管理列表 */
        getList() {
            this.loading = true;
            this.queryParams.params = {};
            if (null != this.daterangeUpdateTime && '' != this.daterangeUpdateTime) {
                this.queryParams.params["beginUpdateTime"] = this.daterangeUpdateTime[0];
                this.queryParams.params["endUpdateTime"] = this.daterangeUpdateTime[1];
            }
            listRegion(this.queryParams).then(response => {
                this.regionList = this.handleTree(response.data, "regionId", "parentRegionId");
                this.loading = false;
            });
        },
        /** 转换地区管理数据结构 */
        normalizer(node) {
            if (node.children && !node.children.length) {
                delete node.children;
            }
            return {
                id: node.regionId,
                label: node.regionName,
                children: node.children
            };
        },
        /** 查询地区管理下拉树结构 */
        getTreeselect() {
            listRegion().then(response => {
                this.regionOptions = [];
                const data = {regionId: 0, regionName: '顶级节点', children: []};
                data.children = this.handleTree(response.data, "regionId", "parentRegionId");
                this.regionOptions.push(data);
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                regionId: null,
                regionCode: null,
                parentRegionId: null,
                regionName: null,
                regionLevel: null,
                completeRegionId: null,
                completeRegionCode: null,
                completeRegionName: null,
                createTime: null,
                createBy: null,
                updateTime: null,
                updateBy: null,
                delFlag: null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.daterangeUpdateTime = [];
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 新增按钮操作 */
        handleAdd(row) {
            this.reset();
            this.getTreeselect();
            if (row != null && row.regionId) {
                this.form.parentRegionId = row.regionId;
            } else {
                this.form.parentRegionId = 0;
            }
            this.open = true;
            this.title = "添加地区管理";
        },
        /** 展开/折叠操作 */
        toggleExpandAll() {
            this.refreshTable = false;
            this.isExpandAll = !this.isExpandAll;
            this.$nextTick(() => {
                this.refreshTable = true;
            });
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.loading = true;
            this.reset();
            this.getTreeselect();
            if (row != null) {
                this.form.parentRegionId = row.parentRegionId;
            }
            getRegion(row.regionId).then(response => {
                this.loading = false;
                this.form = response.data;
                this.open = true;
                this.title = "修改地区管理";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    this.buttonLoading = true;
                    if (this.form.regionId != null) {
                        updateRegion(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        }).finally(() => {
                            this.buttonLoading = false;
                        });
                    } else {
                        addRegion(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        }).finally(() => {
                            this.buttonLoading = false;
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            this.$modal.confirm('是否确认删除地区管理编号为"' + row.regionId + '"的数据项？').then(() => {
                this.loading = true;
                return delRegion(row.regionId);
            }).then(() => {
                this.loading = false;
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {
            }).finally(() => {
                this.loading = false;
            });
        }
    }
};
</script>
